import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, Divider, Badge } from 'antd';
import '@/assets/css/settings';
import * as DingTalkSettingsService from '../../axios/DingTalkSettings'
import { BasicLayout, BasicLayoutSearch } from '../../components/BasicLayout';
import { BasicPagination, compareNum, TableCustomize, openSuccessModal, openModalMessage, compareString } from '../../components/TableCustomize'
import { withPermission } from '../../components/withpermission';
import SearchForm from './SearchForm';
import AddForm from './AddForm';
import SettingsForm from './SettingsForm';
const CreateButton = withPermission(Button, 'create')

class Demo extends Component {
    state = {
        dataSource: [],
        visible: false,
        advanced: false,
        searchItem: {},
        modalTitle: '新增钉钉推送配置',
        formData: {},
        drawerVisible: false,
        drawerVisible1: false,
        drawerTitle: '钉钉推送设置',
        pageSize: 10,
        pageNum: 1,
        total: 0,
        columns: [
            {
                title: '序号',
                dataIndex: 'id',
                width: 100,
                render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>,
            },

            {
                title: '功能编码',
                width: 150,
                dataIndex: 'functionCode',
            },
            {
                title: '功能名称',
                width: 150,
                // allowEllipsis: true,
                dataIndex: 'functionName',
                sorter: (a, b) => compareString(a.functionName, b.functionName)
            },
            {
                title: '描述',
                width: 350,
                dataIndex: 'describe',
            },
            {
                title: '推送类型',
                width: 150,
                dataIndex: 'pushType',
                render: (text) => text === 1 ? '个人/多人' : text === 2 ? '群' : text === 3 ? '个人和群' : '',
                sorter: (a, b) => compareNum(a.pushType, b.pushType)
            },
            {
                title: '状态',
                width: 150,
                dataIndex: 'status',
                render: (text) => text === 1 ? <Badge status="error" text={'停用'} /> : text === 0 ? <Badge status='success' text={'启用'} /> : '',
                sorter: (a, b) => compareNum(a.status, b.status)
            },
            {
                title: '操作',
                // width: 150,
                dataIndex: 'opts',
                render: (text, record) => {
                    return <>
                        <a onClick={() => { this.showDrawer1(record) }}>查看/编辑推送设置</a>
                        <Divider type='vertical' />
                        <a onClick={() => { this.startOrEnd(record) }}>{record.status === 1 ? '启用' : '停用'}</a>
                    </>
                }
            }
        ],
        selectedRowKeys: [],
        selectedRows: [],
        dataSourcePrecedure: [],
        userListPrecedure: [],
        buttonLoading: false
    };
    componentDidMount() {
        this.fetch();
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    //初始化加载数据
    fetch = (pageNum = 1, pageSize = 100) => {
        this.setState({ loading: true });
        const { searchItem } = this.state;
        searchItem.pageNum = pageNum;
        searchItem.pageSize = pageSize;
        DingTalkSettingsService.selectList(searchItem).then(res => {
            this.setState({ loading: false })
            if (res.data.data.code !== 200) {
                openModalMessage('warning', res.data.data.msg);
                return;
            }
            this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize });
        }).catch(err => {
            openModalMessage('error', err.message);
        })
    }
    //添加修改菜单提交
    submitMenu = () => {
        this.formAdd.validateFields((err, value) => {
            if (err) return;
            console.log(value)
        })
    }
    onHandleOk = () => {
        this.formDrawer.validateFields((err, value) => {
            if (err) return;
            DingTalkSettingsService.add(value).then(res => {
                if (res.data.code !== 200) {
                    openModalMessage('warning', res.data.msg);
                    return;
                }
                openSuccessModal(res.data.msg);
                this.handleCancel();
            }).catch(err => {
                openModalMessage('error', err.message);
            })
        })
    }

    onHandleOk1 = () => {
        const { dataSourcePrecedure, userListPrecedure, formData } = this.state;
        this.formDrawer1.validateFields((err, value) => {
            if (err) return;
            this.setState({ buttonLoading: true })
            console.log(value)
            console.log(dataSourcePrecedure, userListPrecedure)
            let data = { ...formData, ...value }
            if (value.pushType === 1) {
                if (!userListPrecedure.length) {
                    openModalMessage('warning', '请选择要推送的用户！');
                    this.setState({ buttonLoading: false });
                    return;
                }
                let str = userListPrecedure.join(',');
                data.pushUser = str;
                data.configurationSublistDTO = [];
            }
            if (value.pushType === 2) {
                let index = 0;
                let arr1 = [];
                let arr2 = [];
                let arr = [];
                for (var item of dataSourcePrecedure) {
                    if (typeof (item.id) === 'string') {
                        arr1.push(item);
                    } else if (typeof (item.id) === 'number') {
                        arr2.push(item)
                    }
                }
                for (var objs of arr1) {
                    if (!objs.groupName) {
                        delete (objs.groupName);
                    }
                    if (!objs.remark) {
                        delete (objs.remark);
                    }
                    if (!objs.secret) {
                        delete (objs.secret);
                    }
                    if (!objs.webhook) {
                        delete (objs.webhook);
                    }
                }
                for (var objs2 of arr1) {
                    if (Object.keys(objs2).length <= 1) {
                        index++;
                    } else {
                        arr.push(objs2);
                    }

                }
                if (index === 5) {
                    openModalMessage('warning', '请填写要推送的群组数据！');
                    this.setState({ buttonLoading: false });
                    return;
                }
                for (var objs3 of arr) {
                    if (!objs3.groupName || !objs3.secret || !objs3.webhook) {
                        openModalMessage('warning', '请将信息补充完整！');
                        this.setState({ buttonLoading: false });
                        return;
                    }
                }
                data.pushUser = '';
                let arr3 = [...arr2, ...arr];
                for (var ii of arr3) {
                    if (!ii.groupName || !ii.secret || !ii.webhook) {
                        openModalMessage('warning', '请将信息补充完整！');
                        this.setState({ buttonLoading: false });
                        return;
                    }
                }
                for (var items of arr3) {
                    if (typeof (items.id) === 'string') {
                        delete (items.id)
                    }
                }
                data.configurationSublistDTO = arr3;
            }
            if (value.pushType === 3) {
                if (!userListPrecedure.length) {
                    openModalMessage('warning', '请选择要推送的用户！');
                    this.setState({ buttonLoading: false });
                    return;
                }
                let index = 0;
                let arr1 = [];
                let arr2 = [];
                let arr = [];
                for (var objs of dataSourcePrecedure) {
                    if (!objs.groupName) {
                        delete (objs.groupName);
                    }
                    if (!objs.remark) {
                        delete (objs.remark);
                    }
                    if (!objs.secret) {
                        delete (objs.secret);
                    }
                    if (!objs.webhook) {
                        delete (objs.webhook);
                    }
                }
                for (var item of dataSourcePrecedure) {
                    if (typeof (item.id) === 'string') {
                        arr1.push(item);
                    } else if (typeof (item.id) === 'number') {
                        arr2.push(item)
                    }
                }
                for (var objs2 of arr1) {
                    if (Object.keys(objs2).length <= 1) {
                        index++;
                    } else {
                        arr.push(objs2);
                    }

                }
                if (index === 5) {
                    openModalMessage('warning', '请填写要推送的群组数据！');
                    this.setState({ buttonLoading: false });
                    return;
                }
                for (var objs3 of arr) {
                    if (!objs3.groupName || !objs3.secret || !objs3.webhook) {
                        openModalMessage('warning', '请将信息补充完整！');
                        this.setState({ buttonLoading: false });
                        return;
                    }
                }
                let str = userListPrecedure.join(',');
                let arr3 = [...arr2, ...arr];
                for (var ii of arr3) {
                    if (!ii.groupName || !ii.secret || !ii.webhook) {
                        openModalMessage('warning', '请将信息补充完整！');
                        this.setState({ buttonLoading: false });
                        return;
                    }
                }
                for (var items of arr3) {
                    if (typeof (items.id) === 'string') {
                        delete (items.id)
                    }
                }
                data.pushUser = str;
                data.configurationSublistDTO = arr3;
            }
            console.log(data)
            DingTalkSettingsService.add(data).then(res => {
                this.setState({ buttonLoading: false })
                if (res.data.code !== 200) {
                    openModalMessage('warning', res.data.msg);
                    return;
                }
                openSuccessModal(res.data.msg);
                this.handleCancel();
                this.setState({
                    dataSourcePrecedure: [],
                    userListPrecedure: [],
                    formData: {}
                })
            })
        })
    }
    showDrawer = () => {
        this.setState({
            drawerVisible: true,
        });
    }
    showDrawer1 = (record) => {
        this.setState({
            drawerVisible1: true,
            formData: record
        });
    }

    handleCancel = e => {
        this.formAdd && this.formAdd.resetFields();
        this.formDrawer && this.formDrawer.resetFields();
        this.formDrawer1 && this.formDrawer1.resetFields();
        this.setState({
            visible: false,
            btnDrawer: false,
            drawerVisible: false,
            drawerVisible1: false,
            selectedRowKeys: [],
            selectedRows: []
        });
        this.fetch();
    };


    handleSearch = value => {
        this.setState({ searchItem: value }, this.fetch);
    };

    onHandleAdvanced = () => {
        this.setState({ advanced: !this.state.advanced })
    }
    loadData = (value, dataSource) => {
        console.log(value, dataSource)
    }
    chooseRow = (record) => {
        this.setState({ selectedRowKeys: [record.id], selectedRows: [record] })
    }
    deleteDataSource = () => {
        const { selectedRowKeys, selectedRows } = this.state;
        if (!selectedRowKeys.length) {
            openModalMessage('warning', '请选择要删除的数据！');
            return;
        }
        const that = this
        Modal.confirm({
            title: '确认删除【' + selectedRows[0].functionCode + '】数据吗？',
            onOk: async () => {
                DingTalkSettingsService.del(selectedRowKeys[0]).then(res => {
                    if (res.data.code !== 200) {
                        openModalMessage('warning', res.data.msg);
                        return;
                    }
                    openSuccessModal(res.data.msg);
                    that.fetch();
                    that.setState({ selectedRowKeys: [], selectedRows: [] })
                }).catch(err => {
                    openModalMessage('error', err.message);
                })
            },
            onCancel() {

            }
        })
    }
    startOrEnd = (record) => {
        const that = this;
        Modal.confirm({
            title: `确认${record.status === 1 ? '启用' : '停用'}【${record.functionCode}】数据吗？`,
            onOk: async () => {
                record.status = record.status === 1 ? 0 : 1;
                DingTalkSettingsService.updateStatus(record).then(res => {
                    if (res.data.code !== 200) {
                        openModalMessage('warning', res.data.msg);
                        return;
                    }
                    openSuccessModal(res.data.msg);
                    that.fetch();
                    that.setState({ selectedRowKeys: [], selectedRows: [] })
                }).catch(err => {
                    openModalMessage('error', err.message);
                })
            },
            onCancel() {

            }
        })
    }
    saveProcedure = (type, value) => {
        if (type === 1) {
            this.setState({ dataSourcePrecedure: value });
        }
        if (type === 2) {
            this.setState({ userListPrecedure: value });
        }
    }
    test = () => {
        const { selectedRows } = this.state;
        if (!selectedRows.length) {
            openModalMessage('warning', '请选择要推送测试的数据！');
            return;
        }
        const that = this;
        Modal.confirm({
            title: `确定推送【${selectedRows[0].functionName}】测试吗？`,
            onOk: async () => {
                let obj = {
                    whether: 2,
                    "title": "多人消息测试",
                    "text": "# 一级标题\n## 二级标题\n### 三级标题\n#### 四级标题\n##### 五级标题\n###### 六级标题\n链接[百度](http://www.baidu.com)\n\n图片\n![](https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1634199951/p158171.png)\n![](https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/0634199951/p158167.png)",
                    functionName: selectedRows[0].functionName
                }
                await DingTalkSettingsService.dingPushNews(obj).then(res => {
                    if (res.data.code !== 200) {
                        openModalMessage('warning', res.data.msg);
                        return;
                    }
                    openSuccessModal(res.data.msg);
                    that.fetch();
                }).catch(err => {
                    openModalMessage('error', err.message);
                })
            },
            onCancel() { }
        })
    }
    resetForm = () => {
        this.formSearch && this.formSearch.resetFields();
        this.setState({ searchItem: {} }, this.fetch);
    }
    render() {
        const { loading, dataSource, formData, modalTitle, drawerVisible, drawerTitle, drawerVisible1, advanced, columns, pageNum, pageSize, total, selectedRowKeys, buttonLoading } = this.state;
        const rowSelection = {
            type: 'radio',
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ selectedRowKeys, selectedRows })
            }
        }
        return (
            <div>
                <BasicLayoutSearch>
                    <SearchForm onSearch={this.handleSearch}
                        onClick={this.onHandleAdvanced}
                        advanced={advanced}
                        resetForm={this.resetForm}
                        ref={node => (this.formSearch = node)} />
                </BasicLayoutSearch>
                <BasicLayout buttons={[<Button key={0} onClick={this.showDrawer} type='primary' icon='plus'>新增</Button>, <Button key={1} type='danger' icon='delete' onClick={this.deleteDataSource}>删除</Button>, <Button key={2} onClick={this.test} type='primary' icon='upload'>推送测试</Button>]} name="钉钉推送配置" icon="table">
                    <TableCustomize
                        columns={columns}
                        rowKey={(record) => record.id}
                        dataSource={dataSource}
                        pagination={false}
                        loading={loading}
                        allowDrafting={true}
                        allowRowEdit
                        allowEditable={this.loadData}
                        rowSelection={rowSelection}
                        onRow={(record) => ({
                            onClick: this.chooseRow.bind(this, record)
                        })} />
                    <BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
                </BasicLayout>

                <Drawer width={460} visible={drawerVisible} title={modalTitle} onClose={this.handleCancel} destroyOnClose={true} maskClosable={false}>
                    <AddForm
                        onOk={this.onHandleOk}
                        ref={node => (this.formDrawer = node)}
                        onClose={this.handleCancel}
                    />
                    <div
                        style={{
                            position: 'absolute',
                            right: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button onClick={this.handleCancel} style={{ marginRight: 10 }}>{'取消'}</Button>
                        <Button type="primary" onClick={this.onHandleOk}>
                            {'确认'}
                        </Button>
                    </div>

                </Drawer>

                <Drawer width={'85%'} visible={drawerVisible1} title={drawerTitle} onClose={this.handleCancel} destroyOnClose={true} maskClosable={false}>
                    <SettingsForm
                        formData={formData}
                        onOk={this.onHandleOk1}
                        ref={node => (this.formDrawer1 = node)}
                        onClose={this.handleCancel}
                        onSave={this.saveProcedure}
                    />
                    <div
                        style={{
                            position: 'absolute',
                            right: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button onClick={this.handleCancel} style={{ marginRight: 10 }}>{'取消'}</Button>
                        <Button type="primary" onClick={this.onHandleOk1} loading={buttonLoading}>
                            {'确认'}
                        </Button>
                    </div>

                </Drawer>
            </div>
        );
    }
}
export default Form.create()(Demo);